package cn.yanhu.kuwanapp.utils

import android.text.Spanned
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.BindingAdapter
import cn.woochen.comlib.util.GlideUtil
import cn.woochen.comlib.util.ext.toHtml

/**
 *
 * 类描述：
 * 创建人：woochen
 * 创建时间：2020/12/25 7:29 PM
 * 修改备注：
 **/
@BindingAdapter("android:text")
fun setText(view: TextView, text: CharSequence?): Unit {
    val oldText = view.text
    if (text === oldText || text == null && oldText.isEmpty()) {
        return
    }
    if (text is Spanned) {
        if (text == oldText) {
            return  // No change in the spans, so don't set anything.
        }
    } else if (!haveContentsChanged(text, oldText)) {
        return  // No content changes, so don't set anything.
    }
    text?.let {
        if (it.contains("<") && it.contains(">")) {
            view.text = text.toString().toHtml()
        } else view.text = text
    }
}

private fun haveContentsChanged(str1: CharSequence?, str2: CharSequence?): Boolean {
    if (str1 == null != (str2 == null)) {
        return true
    } else if (str1 == null) {
        return false
    }
    val length = str1.length
    if (length != str2!!.length) {
        return true
    }
    for (i in 0 until length) {
        if (str1[i] != str2[i]) {
            return true
        }
    }
    return false
}

@BindingAdapter(value = ["imageUrl", "isCircle", "isRec", "angle"], requireAll = false)
fun loadImage(view: ImageView, url: Any?, isCircle: Boolean = false, isRec: Boolean = false, angle: Float = 0f) {
    if (isCircle){
        GlideUtil.loadCircle(view.context, url, view)
    }else if (isRec){
        GlideUtil.loadRec(view.context,url,view,angle)
    }else{
        GlideUtil.load(view.context, url, view)
    }
}